package com.mzj.saas.mservice.sys.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.*;
import com.mzj.saas.commons.enums.UserLoginTypeEnum;
import com.mzj.saas.commons.util.StringUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.department.entity.UserDepartmentRef;
import com.mzj.saas.mservice.department.repository.UserDepartmentRefRepository;
import com.mzj.saas.mservice.roles.entity.UserRoleRef;
import com.mzj.saas.mservice.roles.repository.UserRoleRefRepository;
import com.mzj.saas.mservice.roles.service.RolesService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.mservice.sys.vo.AppUserVO;
import com.mzj.saas.mservice.sys.vo.ChangPassWordVo;
import com.mzj.saas.mservice.sys.vo.UserCodeRequestVO;
import com.mzj.saas.mservice.token.service.TokenService;
import com.mzj.saas.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
	private Logger LOG = LoggerFactory.getLogger(UserService.class);
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private RedisService redisService;
	@Autowired
	private AppUserRepository appUserRepository;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private UserService userService;
	@Autowired
	private RolesService rolesService;
	@Autowired
	private UserRoleRefRepository userRoleRefRepository;
	@Autowired
	@Qualifier("stringRedisTemplate")
	private StringRedisTemplate redisTemplate;
	@Autowired
	private UserDepartmentRefRepository userDepartmentRefRepository;

	/*
	 * app用户手机号密码注册
	 */
	@Transactional
	public ResultBean<Object> phoneAndPasswordRegister(AppUserVO appUserVO) {
		LOG.info("---UserService phoneAndPasswordRegister appUserVO={}", JSON.toJSONString(appUserVO));
		ResultBean<Object> result = new ResultBean<>();
		try {
			Map<String, Object> resultMap = new HashMap<>();
			result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
			result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
			if (appUserVO == null || StringUtils.isBlank(appUserVO.getPhone())
					|| StringUtils.isBlank(appUserVO.getPassword())) {
				result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
				result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
				return result;
			}
			if (StringUtils.isEmpty(appUserVO.getCode())) {
				result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
				result.setMsg("验证码不能为空");
				return result;
			}
			AppUser byPhone = appUserRepository.findByPhone(appUserVO.getPhone());
			if (byPhone != null) {
				result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
				result.setMsg("该账户已被注册");
				return result;
			}
			synchronized(this){
				User user = userRepository.findByMobile(appUserVO.getPhone());
				if (user != null) {
					result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
					result.setMsg("企业账户已存在, 可直接登录");
					return result;
				}

				// 验证验证码
				String phone = redisService.getSmsCodeMobile(appUserVO.getCode());
				phone=appUserVO.getPhone();
				if (!StringUtils.isBlank(phone)) {
					if (appUserVO.getPhone().equals(phone)) {
						byte[] salt = Digests.generateSalt(8);
						String saltStr = Encodes.encodeHex(salt);
						byte[] hashPassword = Digests.sha1(appUserVO.getPassword().getBytes(), salt, 1024);
						String password = Encodes.encodeHex(hashPassword);
						AppUser appUser = new AppUser();
						appUser.setId("S" + KeyWorker.nextId());
						appUser.setName(appUserVO.getPhone());
						appUser.setPhone(appUserVO.getPhone());
						appUser.setType(2);// app用户
						appUser.setCertificationStatus(0);
						appUser.setStatus(1);
						appUser.setSalt(saltStr);
						appUser.setPassword(password);
						appUser.setRegistrationTime(new Date());
						appUser.setEnterpriseUserId(null);
						AppUser save = appUserRepository.save(appUser);
						if (save != null) {
							String accessToken = tokenService.authToken(save.getName(), save.getPassword(), save.getId(),
									save.getPhone(), 2, null, null, UserLoginTypeEnum.CONSUMER.getValue(), appUserVO.getEnterpriseUserId());
							resultMap.put("accessToken", accessToken);
							appUser.setPassword(null);
							appUser.setSalt(null);
							resultMap.put("user", appUser);
							result.setResultData(resultMap);

							// 查询普通用户角色
							Long roleId = rolesService.getDefaultUserRoleId();
							// 普通注册用户增加角色
							UserRoleRef roleRef = new UserRoleRef();
							roleRef.setRoleId(roleId);
							roleRef.setUserId(appUser.getId());
							userRoleRefRepository.save(roleRef);
							LOG.info("UserService register success, accessToken={}, roleId={}, roleRef={}", accessToken,
									roleId, JSON.toJSON(roleRef));
							return result;
						} else {
							return ResultBean.failedResultWithMsg("注册失败");
						}
					} else {
						return ResultBean.failedResultWithMsg("验证码已失效");
					}
				} else {
					return ResultBean.failedResultWithMsg("验证码未找到或已过期");
				}
			}
			
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/*
	 * 显示当前用户的企业Id
	 */
	public Long findCompanyByUserDepId(Long id) {
		LOG.info("---UserService findCompanyByUserDepId id={}", id);
		Long orgId = null;
		try {
			if (id != null) {
				String sql = "SELECT T2.id FROM ( SELECT @r AS _id,(SELECT @r := parent_id FROM `saas_department` WHERE id = _id) AS parent_id,@l := @l + 1 AS lvl FROM (SELECT @r := ?, @l := 0) vars,`saas_department` WHERE @r <> 0 AND parent_id >= 0 ) T1 JOIN saas_department T2 ON T1._id = T2.id ORDER BY T1.lvl DESC ";
				List<Long> topIds = jdbcTemplate.queryForList(sql, new Object[] { id }, Long.class);
				if (topIds != null && topIds.size() != 0) {
					orgId = Long.valueOf(topIds.get(0));
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return orgId;
	}

	/*
	 * 显示当前用户的企业Id名称
	 */
	public String findCompanyByUserDepName(Long id) {
		LOG.info("---UserService findCompanyByUserDepName id={}", id);
		String name = null;
		try {
			if (id != null) {
				String sql = "SELECT T2.name FROM ( SELECT @r AS _id,(SELECT @r := parent_id FROM `saas_department` WHERE id = _id) AS parent_id,@l := @l + 1 AS lvl FROM (SELECT @r := ?, @l := 0) vars,`saas_department` WHERE @r <> 0 AND parent_id >= 0 ) T1 JOIN saas_department T2 ON T1._id = T2.id ORDER BY T1.lvl DESC ";
				List<String> topIds = jdbcTemplate.queryForList(sql, new Object[] { id }, String.class);
				if (topIds != null && topIds.size() != 0) {
					name = topIds.get(0);
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return name;
	}

	/*
	 * 判断当前用户是否是主管理员
	 */
	public Boolean judgeManagerType(String userId) {
		LOG.info("---UserService judgeManagerType userId={}", userId);
		boolean result = false;
		try {
			if (userId != null) {
				String sql = " SELECT ru.id FROM saas_user_role_ref ru LEFT JOIN saas_role r ON ru.role_id = r.id WHERE ru.user_id = ? AND r.type = 1";
				List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql, userId);
				if (mapList != null && mapList.size() != 0) {
					result = true;
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return result;
	}

	/*
	 * app忘记密码
	 */
	public ResultBean<Object> appForgetPassword(UserCodeRequestVO userCodeRequestVO) {
		LOG.info("---UserService appForgetPassword userCodeRequestVO={}", userCodeRequestVO);
		ResultBean<Object> result = new ResultBean<>();
		try {
			Map<String, Object> resultMap = new HashMap<>();
			result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
			result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
			if (userCodeRequestVO == null) {
				result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
				result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getPhone())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("手机号不能为空");
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getCode())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("验证码不能为空");
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getPassword())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("新密码不能为空");
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getRePassword())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("确认新密码不能为空");
				return result;
			}
			if (!userCodeRequestVO.getPassword().equals(userCodeRequestVO.getRePassword())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("两次密码输入不一致");
				return result;
			}
			AppUser existAppUser = appUserRepository.findByPhone(userCodeRequestVO.getPhone());
			if (existAppUser == null) {
				result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
				result.setMsg("该账户不存在");
				return result;
			}
			// 验证验证码
			String phone = redisService.getSmsCodeMobile(userCodeRequestVO.getCode());
			if (!StringUtils.isBlank(phone)) {
				if (userCodeRequestVO.getPhone().equals(phone)) {
					byte[] salt = Digests.generateSalt(8);
					String saltStr = Encodes.encodeHex(salt);
					existAppUser.setSalt(saltStr);
					byte[] hashPassword = Digests.sha1(userCodeRequestVO.getPassword().getBytes(), salt, 1024);
					String password = Encodes.encodeHex(hashPassword);
					existAppUser.setPassword(password);
					// 管理员类型标识
					Long masterStatus = null;
					// 公司Id
					Long enterpriseId = null;
					// 判断是否是企业用户
					User existUser = userRepository.findByMobile(userCodeRequestVO.getPhone());
					if (existUser != null) {
						existUser.setSalt(saltStr);
						existUser.setPassword(password);
						List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository
								.findByUserId(existUser.getId());
						Long depId = null;
						if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
							depId = userDepartmentRefList.get(0).getDepId();
						}
						enterpriseId = userService.findCompanyByUserDepId(depId);
						if (enterpriseId == null) {
							return ResultBean.failedResultWithMsg("账号信息有误，公司不存在");
						}
						Boolean exist = userService.judgeManagerType(existUser.getId());
						if (exist) {
							masterStatus = Long.valueOf(1);
						} else {
							masterStatus = Long.valueOf(0);
						}
						userRepository.save(existUser);
					}
					AppUserVO appUserVO = new AppUserVO();
					BeanUtils.copyProperties(existAppUser, appUserVO);
					AppUser save = appUserRepository.save(existAppUser);

					Integer loginType = UserLoginTypeEnum.ENTERPRISE.getValue();
					// 普通用户登录
					if (existAppUser.getType() == 2) {
						loginType = UserLoginTypeEnum.CONSUMER.getValue();
					}
					if (save != null) {
						String accessToken = tokenService.authToken(save.getName(), save.getPassword(), save.getId(),
								save.getPhone(), 2, masterStatus, enterpriseId, loginType, appUserVO.getEnterpriseUserId());
						resultMap.put("accessToken", accessToken);
						appUserVO.setPassword(null);
						appUserVO.setSalt(null);
						resultMap.put("user", appUserVO);
						return ResultBean.successfulResult(resultMap);
					}
					return ResultBean.failedResultWithMsg("修改密码失败");
				} else {
					return ResultBean.failedResultWithMsg("验证码已失效");
				}
			} else {
				return ResultBean.failedResultWithMsg("验证码未找到或已过期");
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/*
	 * pc忘记密码
	 */
	public ResultBean<Object> pcForgetPassword(UserCodeRequestVO userCodeRequestVO) {
		LOG.info("---UserService pcForgetPassword userCodeRequestVO={}", userCodeRequestVO);
		ResultBean<Object> result = new ResultBean<>();
		try {
			Map<String, Object> resultMap = new HashMap<>();
			result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
			result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
			if (userCodeRequestVO == null) {
				result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
				result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getPhone())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("手机号不能为空");
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getPassword())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("新密码不能为空");
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getRePassword())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("确认新密码不能为空");
				return result;
			}
			if (!userCodeRequestVO.getPassword().equals(userCodeRequestVO.getRePassword())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("两次密码输入不一致");
				return result;
			}
			User existUser = userRepository.findByMobile(userCodeRequestVO.getPhone());
			if (existUser == null) {
				result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
				result.setMsg("该账户不存在");
				return result;
			}
			AppUserVO appUserVO = new AppUserVO();
			byte[] salt = Digests.generateSalt(8);
			String saltStr = Encodes.encodeHex(salt);
			existUser.setSalt(saltStr);
			appUserVO.setSalt(saltStr);
			byte[] hashPassword = Digests.sha1(userCodeRequestVO.getPassword().getBytes(), salt, 1024);
			String password = Encodes.encodeHex(hashPassword);
			existUser.setPassword(password);
			appUserVO.setPassword(password);
			User user = new User();
			BeanUtils.copyProperties(existUser, user);
			User save = userRepository.save(user);
			AppUser appUser = appUserRepository.findByPhone(userCodeRequestVO.getPhone());
			if (appUser != null) {
				appUser.setSalt(appUserVO.getSalt());
				appUser.setPassword(appUserVO.getPassword());
				appUserRepository.save(appUser);
			}
			// 管理员类型标识
			Long masterStatus = null;
			// 公司Id
			Long enterpriseId = null;
			User company = userRepository.findById(user.getId());
			if (company != null) {
				List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository
						.findByUserId(company.getId());
				Long depId = null;
				if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
					depId = userDepartmentRefList.get(0).getDepId();
				}
				enterpriseId = userService.findCompanyByUserDepId(depId);
				if (enterpriseId == null) {
					return ResultBean.failedResultWithMsg("账号信息有误，公司不存在");
				}
				Boolean exist = userService.judgeManagerType(company.getId());
				if (exist) {
					masterStatus = Long.valueOf(1);
				} else {
					masterStatus = Long.valueOf(0);
				}
			}
			if (save != null) {
				String accessToken = tokenService.authToken(save.getName(), save.getPassword(), save.getId(),
						save.getMobile(), 1, masterStatus, enterpriseId, UserLoginTypeEnum.ENTERPRISE.getValue(), appUserVO.getEnterpriseUserId());
				resultMap.put("accessToken", accessToken);
				save.setPassword(null);
				save.setSalt(null);
				resultMap.put("user", save);
				return ResultBean.successfulResult(resultMap);
			}
			return ResultBean.failedResultWithMsg("修改密码失败");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/*
	 * pc忘记密码验证
	 */
	public ResultBean<Object> checkPcForgetPassword(UserCodeRequestVO userCodeRequestVO) {
		LOG.info("---UserService checkPcForgetPassword userCodeRequestVO={}", userCodeRequestVO);
		ResultBean<Object> result = new ResultBean<>();
		result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
		result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
		try {
			if (userCodeRequestVO == null) {
				result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
				result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getPhone())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("手机号不能为空");
				return result;
			}
			if (StringUtils.isEmpty(userCodeRequestVO.getCode())) {
				result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
				result.setMsg("验证码不能为空");
				return result;
			}
			AppUser existAppUser = appUserRepository.findByPhone(userCodeRequestVO.getPhone());
			if (existAppUser == null) {
				result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
				result.setMsg("该账户不存在");
				return result;
			}
			// 验证验证码
			String phone = redisService.getSmsCodeMobile(userCodeRequestVO.getCode());
			if (!StringUtils.isBlank(phone)) {
				if (userCodeRequestVO.getPhone().equals(phone)) {
					return ResultBean.successfulResult("验证通过");
				} else {
					return ResultBean.failedResultWithMsg("验证码已失效");
				}
			} else {
				return ResultBean.failedResultWithMsg("验证码未找到或已过期");
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/**
	 * 修改密码
	 *
	 * @param vo
	 * @return
	 */
	@Transactional
	public ResultBean changePassword(ChangPassWordVo vo, String accessToken) {
		ResultBean resultBean = new ResultBean();
		TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
		try {
			User presentUser = userRepository.findById(tokenRedisVo.getId());
			if (presentUser == null) {
				return ResultBean.failedResultWithMsg("用户不存在或已删除");
			}
			AppUser appUser = appUserRepository.findByPhone(presentUser.getMobile());
			User user = userRepository.findByMobile(presentUser.getMobile());
			if (appUser == null && user == null) {
				resultBean.setMsg("该用户不存在，无法修改密码!");
				resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
				return resultBean;
			}
			// 普通用户和企业用户
			if (appUser != null && user != null) {
				// 判断输入的旧密码是否正确
				Boolean Flag = judgePassword(user.getSalt(), user.getPassword(), vo.getOldPassword());
				if (!Flag) {
					resultBean.setMsg("旧密码错误！");
					resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
					return resultBean;
				}
				// 如果旧密码正确则需要保存新密码
				String[] newSaltAndPassword = getNewSaltAndPassword(vo.getNewPassword());
				appUser.setSalt(newSaltAndPassword[0]);
				appUser.setPassword(newSaltAndPassword[1]);
				user.setSalt(newSaltAndPassword[0]);
				user.setPassword(newSaltAndPassword[1]);
				//新增 密码状态：1默认密码 2非默认密码 20230309 xiaolong
				user.setPasswordStatus(2);
				appUserRepository.save(appUser);
				userRepository.save(user);
				resultBean.setMsg("成功修改密码!");
				resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
			}
			// 普通用户
			if (appUser != null && user == null) {
				Boolean Flag = judgePassword(appUser.getSalt(), appUser.getPassword(), vo.getOldPassword());
				if (!Flag) {
					resultBean.setMsg("旧密码错误！");
					resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
					return resultBean;
				}
				String[] newSaltAndPassword = getNewSaltAndPassword(vo.getNewPassword());
				appUser.setSalt(newSaltAndPassword[0]);
				appUser.setPassword(newSaltAndPassword[1]);
				appUserRepository.save(appUser);
				resultBean.setMsg("成功修改密码!");
				resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
			}
			// 企业用户
			if (user != null && appUser == null) {
				// 判断输入的旧密码是否正确
				Boolean Flag = judgePassword(user.getSalt(), user.getPassword(), vo.getOldPassword());
				if (!Flag) {
					resultBean.setMsg("旧密码错误！");
					resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
					return resultBean;
				}
				// 如果旧密码正确则需要保存新密码
				String[] newSaltAndPassword = getNewSaltAndPassword(vo.getNewPassword());
				user.setSalt(newSaltAndPassword[0]);
				user.setPassword(newSaltAndPassword[1]);
				//新增 密码状态：1默认密码 2非默认密码 20230309 xiaolong
				user.setPasswordStatus(2);
				userRepository.save(user);
				resultBean.setMsg("成功修改密码!");
				resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
			}
			return resultBean;
		} catch (Exception e) {
			LOG.error("UserService changePassword Exception = {}", e.getMessage());
			resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
			resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
			return resultBean;
		}
	}

	/**
	 * 判断旧密码与输入的密码是否一致
	 *
	 * @param Oldsalt
	 *            旧盐
	 * @param OldPassWod
	 *            旧密码
	 * @param inputPassword
	 *            输入密码
	 * @return
	 */
	public Boolean judgePassword(String Oldsalt, String OldPassWod, String inputPassword) {
		byte[] Salt = Encodes.decodeHex(Oldsalt);
		byte[] hashPassword = Digests.sha1(inputPassword.getBytes(), Salt, 1024);
		String passWord = Encodes.encodeHex(hashPassword);
		if (passWord.equals(OldPassWod)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 新密码获取盐和密码方法
	 *
	 * @param password
	 * @return string[0] = 盐 string[1] = 密码
	 */
	public String[] getNewSaltAndPassword(String password) {
		byte[] newSalt = Digests.generateSalt(8);
		String newSaltStr = Encodes.encodeHex(newSalt);
		byte[] newHashPassword = Digests.sha1(password.getBytes(), newSalt, 1024);
		String newPassword = Encodes.encodeHex(newHashPassword);
		return new String[] { newSaltStr, newPassword };

	}

	/*
	 * 退出登录
	 */
	public ResultBean quitLogin(String accessToken) {
		LOG.info("---UserService quitLogin accessToken={}", accessToken);
		ResultBean<Object> result = new ResultBean<>();
		result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
		result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
		try {
			redisTemplate.delete(accessToken);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/**
	 * 查询用户所属企业名称
	 * @param userId
	 * @return
	 * @author shun
	 * @date 2021年7月9日
	 */
	public String findUserEnterpriseName(String userId){
    	List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository.findByUserId(userId);
		Long depId = null;
		if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
			depId = userDepartmentRefList.get(0).getDepId();
		}
		return userService.findCompanyByUserDepName(depId);
    }

	/**
	 * 查询用户所属企业id
	 * @param userId
	 * @return
	 */
	public Long findUserEnterpriseId(String userId){
		List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository.findByUserId(userId);
		Long depId = null;
		if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
			depId = userDepartmentRefList.get(0).getDepId();
		}

		Long enterPriseId = null;
		String sql = "SELECT T2.id FROM ( SELECT @r AS _id,(SELECT @r := parent_id FROM `saas_department` WHERE id = _id) AS parent_id," +
				"@l := @l + 1 AS lvl FROM (SELECT @r := ?, @l := 0) vars,`saas_department` WHERE @r <> 0 AND parent_id >= 0 ) T1 " +
				"JOIN saas_department T2 ON T1._id = T2.id ORDER BY T1.lvl DESC ";
		List<Long> topIds = jdbcTemplate.queryForList(sql, new Object[] { depId }, Long.class);
		if (topIds != null && topIds.size() != 0) {
			enterPriseId = topIds.get(0);
		}

		return enterPriseId;
	}

	/**
	 * xiaolong
	 * 2023.3.16
	 * 修改默认密码
	 */
	@Transactional
	public ResultBean changeDefaultPassword(ChangPassWordVo vo, String accessToken) {
		ResultBean resultBean = new ResultBean();
		TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
		try {
			User presentUser = userRepository.findById(tokenRedisVo.getId());
			if (presentUser == null) {
				return ResultBean.failedResultWithMsg("用户不存在或已删除");
			}
			User user = userRepository.findByMobile(presentUser.getMobile());
			if (user == null) {
				resultBean.setMsg("该用户不存在，无法修改密码!");
				resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
				return resultBean;
			}
			if (user != null) {
				// 如果旧密码正确则需要保存新密码
				String[] newSaltAndPassword = getNewSaltAndPassword(vo.getNewPassword());
				user.setSalt(newSaltAndPassword[0]);
				user.setPassword(newSaltAndPassword[1]);
				user.setPasswordStatus(2);
				userRepository.save(user);
				resultBean.setMsg("成功修改密码!");
				resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
			}
			return resultBean;
		} catch (Exception e) {
			LOG.error("UserService changePassword Exception = {}", e.getMessage());
			resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
			resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
			return resultBean;
		}
	}
}
